<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="isLook ? '查看' : form.pa_id ? '编辑' : '添加'" class="full" v-model="visible" align-center width="1300px" :z-index="2000"
    @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top" :disabled="isLook" :label-width="100">
      <div class="grid grid-cols-4 gap-x-3">
        <el-form-item label="供应商">
          <el-input :value="form.supplier_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="供应商类型">
          <el-input value="1688" disabled></el-input>
        </el-form-item>
        <el-form-item label="结算方式">
          <el-input value="现结" disabled></el-input>
        </el-form-item>
        <el-form-item label="公司主体" prop="company" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.company" :options="options.company" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouse_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.warehouse_id" type="warehouse" placeholder="请输入" class="w-full" @change="getSkuStock" />
        </el-form-item>
        <el-form-item label="退货类型" prop="return_way" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.return_way" :options="options.return_way || []" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="退货方式" prop="return_type" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.return_type" :options="options.return_type || []" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="运费支付方式" prop="deliver_pay_type">
          <VSelect v-model="form.deliver_pay_type" :options="options.deliver_pay_type || []" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="运费承担方" prop="undertake" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.undertake" :options="options.undertake || []" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="收件人" prop="recipient" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.recipient" placeholder="收件人" :maxlength="200" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.phone" placeholder="联系电话" :maxlength="200" />
        </el-form-item>
        <el-form-item label="收货地址" prop="recipient_area_id" class="col-span-2" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <Area v-model="form" field="recipient" :disabled="isLook" />
        </el-form-item>
        <el-form-item label="垫付运费">
          <VSelect v-model="form.advance" :options="options.advance || []" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="备注" class="col-span-full">
          <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"></el-input>
        </el-form-item>
      </div>
      <el-form-item prop="skus.0" class="col-span-full" inline-message :rules="[{ validator: skuValidator, trigger: 'change' }]">
        <template #label>
          <div class="flex items-center">
            <span class="v-title"><span class="text-red-600">*</span> 产品信息</span>
            <el-button v-show="!isLook" class="ml-auto" type="primary" @click="add">添加sku</el-button>
          </div>
        </template>
        <div class="w-full">
          <vxe-table :data="form.skus">
            <vxe-column title="sku" :min-width="80">
              <template #default="{ row }">
                <el-button link type="primary">{{ row.sku }}</el-button>
              </template>
            </vxe-column>
            <vxe-column title="图片" :min-width="80">
              <template #default="{ row }">
                <div class="flex items-center p-2">
                  <VImage :src="row.main_img" size="60px" />
                </div>
              </template>
            </vxe-column>
            <vxe-column title="可退数量" :min-width="80">
              <template #default="{ row }">
                {{ row.available_num }}
              </template>
            </vxe-column>
            <vxe-column title="申请退货数量" :min-width="120">
              <template #default="{ row }">
                <el-input-number v-model="row.return_num" controls-position="right" :min="0" :step="1" :precision="0" />
              </template>
            </vxe-column>
            <vxe-column title="退货原因" :min-width="120">
              <template #default="{ row }">
                <el-input v-model="row.return_reason" placeholder="退货原因"></el-input>
              </template>
            </vxe-column>
            <vxe-column title="退货单价￥" :min-width="120">
              <template #default="{ row }">
                <el-input-number v-model="row.unit_price" controls-position="right" :min="0" :step="0.01" :precision="2" />
              </template>
            </vxe-column>
            <vxe-column title="退货总价" :min-width="80">
              <template #default="{ row }">
                {{ XEUtils.toFixed(row.return_num * row.unit_price, 2) }}
              </template>
            </vxe-column>
            <vxe-column v-if="!isLook" title="操作" :width="80">
              <template #default="{ rowIndex }">
                <el-button link type="primary" @click="form.skus.splice(rowIndex, 1)">移除</el-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <template v-if="isLook">
        <el-button @click="close">关 闭</el-button>
      </template>
      <template v-else>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loadings.create" @click="create(formRef)">确 定</el-button>
      </template>
    </template>
  </el-dialog>
  <Goods ref="goodsRef" @change="goodsChange" />
</template>

<script setup>
import { reactive } from 'vue';
import api from '../api'
import { ElMessage } from 'element-plus'
import Area from '@/components/Area'
import Goods from '@/components/Goods'
import XEUtils from 'xe-utils'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
const isLook = ref(false)
let loadings = reactive({})

// 表单处理
const formRef = ref()
const form = ref({ skus: [] })

const skuValidator = (rule, value, cb) => {
  if (!value) return cb(new Error('不能为空'))
  cb()
}

const getSkuStock = () => {
  const { warehouse_id, skus } = form.value
  if (!skus.length) return
  if (!warehouse_id) {
    ElMessage.error('请选择仓库')
    return
  }
  api.getSkuStock({ warehouse_id, sku: skus.map(d => d.sku) }).then(res => {
    skus.forEach(s => {
      const item = res.data.find(d => d.sku === s.sku) || {}
      s.available_num = item.can_return_num || 0
      return s
    })
  })
}

watch(
  () => form.value.skus.length,
  getSkuStock
)

const goodsChange = (val) => {
  const { skus } = form.value
  let isSome = true
  val.forEach(d => {
    if (!d.supplier_id || skus.length && skus.some(s => s.sku === d.sku || s.supplier_id !== d.supplier_id)) {
      isSome = false
      return
    }
    form.value.skus.push(d)
  })
  !isSome && ElMessage.warning('只能添加相同供应商的产品')
  form.value.s_id = form.value.skus[0].supplier_id
  form.value.supplier_name = form.value.skus[0].supplier_name
  formRef?.value.validateField(['skus.0'])
}

// 打开弹窗
const open = async (id, look) => {
  isLook.value = look
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = {
    skus: []
  }
  loadings = reactive({})
  visible.value = true
  formRef?.value?.resetFields()
  // 编辑
  if (id) {
    const res = await api.detail({ sr_id: id })
    form.value = res.data
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const create = async (formRef) => {
  const validator = await formRef.validate()
  if (!validator) return
  loadings.create = true
  api[form.value.sr_id ? 'edit' : 'create'](form.value).then(res => {
    ElMessage.success('保存成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.create = false
  })
}

// 商品
const goodsRef = ref()
const add = () => {
  goodsRef?.value.open()
}
defineExpose({ open })
</script>